{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e8311baa",
   "metadata": {},
   "source": [
    "$$\n",
    "f = \\frac{f_{\\max}-f_{\\min}}{q_{\\max}-q_{\\min}} (q-Z)=S(q-Z)\\\\\n",
    "q = \\frac fS+Z\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "777ff93d",
   "metadata": {},
   "source": [
    "- unsigned 8 bit\n",
    "    - [0, 255]（q_max, q_min）\n",
    "- signed 8 bit\n",
    "    - [-128, 127]（q_max, q_min)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e6173f22",
   "metadata": {},
   "source": [
    "## quantize"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aaa1dfcd",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:14:16.541441Z",
     "start_time": "2023-07-05T14:14:13.318860Z"
    }
   },
   "outputs": [],
   "source": [
    "from transformers import AutoModel\n",
    "model = AutoModel.from_pretrained('bert-base-uncased')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99551ab4",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:49:57.427112Z",
     "start_time": "2023-07-05T14:49:57.417737Z"
    }
   },
   "outputs": [],
   "source": [
    "model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d27e9e11",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:50:20.658732Z",
     "start_time": "2023-07-05T14:50:20.643717Z"
    }
   },
   "outputs": [],
   "source": [
    "weights = model.state_dict()['encoder.layer.0.attention.self.query.weight']\n",
    "weights.dtype"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5790feca",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:50:23.825669Z",
     "start_time": "2023-07-05T14:50:23.816251Z"
    }
   },
   "outputs": [],
   "source": [
    "# (4h, h)\n",
    "weights.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b542aab4",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:16:25.055670Z",
     "start_time": "2023-07-05T14:16:24.749026Z"
    }
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "86c52d95",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:50:26.835664Z",
     "start_time": "2023-07-05T14:50:26.353195Z"
    }
   },
   "outputs": [],
   "source": [
    "_ = plt.hist(weights.flatten().numpy(), bins=250, )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "459fa0a7",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:50:29.783138Z",
     "start_time": "2023-07-05T14:50:29.776069Z"
    }
   },
   "outputs": [],
   "source": [
    "# signed 8-bit integer\n",
    "zero_point = 0\n",
    "scale = (weights.max() - weights.min())/(127-(-128))\n",
    "scale"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3d70b6c",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:50:32.030900Z",
     "start_time": "2023-07-05T14:50:32.023089Z"
    }
   },
   "outputs": [],
   "source": [
    "(weights/scale + zero_point).round().char()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "634bd6dc",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:50:34.313978Z",
     "start_time": "2023-07-05T14:50:34.308514Z"
    }
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "from torch import quantize_per_tensor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "710238a7",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:50:35.250675Z",
     "start_time": "2023-07-05T14:50:35.243881Z"
    }
   },
   "outputs": [],
   "source": [
    "q_weights = quantize_per_tensor(weights, scale, zero_point, torch.qint8)\n",
    "q_weights.int_repr()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "369c7f54",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:26:06.329258Z",
     "start_time": "2023-07-05T14:26:06.320153Z"
    }
   },
   "outputs": [],
   "source": [
    "q_weights.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f88b02d0",
   "metadata": {},
   "source": [
    "## analysis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6d5290d3",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:50:37.753592Z",
     "start_time": "2023-07-05T14:50:37.405342Z"
    }
   },
   "outputs": [],
   "source": [
    "_ = plt.hist(q_weights.int_repr().flatten().numpy(), bins=250, range=(-60, 60))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "36711b39",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:50:42.578299Z",
     "start_time": "2023-07-05T14:50:40.284362Z"
    }
   },
   "outputs": [],
   "source": [
    "%%timeit\n",
    "weights @ weights.T"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9a5e532d",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:56:53.187851Z",
     "start_time": "2023-07-05T14:56:51.936817Z"
    }
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "from torch.nn.quantized import QFunctional\n",
    "q_fn = QFunctional()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "99eef38a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:56:54.275759Z",
     "start_time": "2023-07-05T14:56:54.268386Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'x86'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# qconfig = torch.quantization.get_default_qconfig('qnnpack')\n",
    "torch.backends.quantized.engine"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bfacb5b5",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-07-05T14:56:22.410054Z",
     "start_time": "2023-07-05T14:56:22.268136Z"
    }
   },
   "outputs": [],
   "source": [
    "# %%timeit \n",
    "q_fn.mul(q_weights, q_weights)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c70332bd",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
